package com.light.applet.common.result;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonView;
import com.light.applet.common.entity.BaseEntityView;
import com.light.applet.common.result.message.ResultMessage;
import lombok.Data;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;

/**
 * @author: 魏彪
 */
@Data
public class Result<T> implements Serializable {

    @JsonView(BaseEntityView.class)
    private String code;

    @JsonView(BaseEntityView.class)
    private String msg;

    @JsonView(BaseEntityView.class)
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private T data;

    public static <T> Result<T> ok() {
        return set(ResultMessage.SUCCESS, null, null);
    }

    public static <T> Result<T> ok(T data) {
        return set(ResultMessage.SUCCESS, null, data);
    }

    public static <T> Result<T> failed() {
        return set(ResultMessage.SERVER_INTERNAL_ERROR, null, null);
    }

    public static <T> Result<T> failed(String msg) {
        return set(ResultMessage.SERVER_INTERNAL_ERROR, msg, null);
    }

    public static <T> Result<T> failed(ResultMessage resultMessage) {
        return set(resultMessage, null, null);
    }

    private static <T> Result<T> set(ResultMessage resultMessage, String msg, T data) {
        Result<T> result = new Result<>();
        result.setCode(resultMessage.code());
        result.setMsg(ObjectUtils.isEmpty(msg) ? resultMessage.message() : msg);
        result.setData(data);
        return result;
    }
}
